package cn.tedu.contorller;

import cn.tedu.dao.BannerDao;
import cn.tedu.dao.CategoryDao;
import cn.tedu.dao.ProductDao;
import cn.tedu.entity.Banner;
import cn.tedu.entity.Category;
import cn.tedu.entity.Product;
import cn.tedu.entity.User;
import cn.tedu.utils.ThUtils;
import org.thymeleaf.context.Context;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "HomeServlet",urlPatterns = {"/HomeServlet"})
public class HomeServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Context context = new Context();

        String cid = request.getParameter("id");
        String keyword = request.getParameter("keyword");

        //获取Session
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        context.setVariable("user",user);

        //获取category中的数据
        CategoryDao dao = new CategoryDao();
        List<Category> list = dao.findAll();
        context.setVariable("list",list);

        //获取banner中的数据
        BannerDao bDao = new BannerDao();
        List<Banner> bList = bDao.findAll();
        context.setVariable("bList",bList);

        //获取Product中的数据
        ProductDao pDao = new ProductDao();
        List<Product> pList;
        if (cid!=null){
            pList = pDao.findByCId(cid);
        }else if (keyword!=null){
            pList = pDao.findByKeyword(keyword);
        }else{
            pList = pDao.findAll();
        }
        context.setVariable("pList",pList);

        //获取最多浏览
        List<Product>viewList = pDao.findViewList();
        context.setVariable("viewList",viewList);

        //获取最多赞
        List<Product>likeList = pDao.findLikeList();
        context.setVariable("likeList",likeList);

        ThUtils.print("home.html",context,response);
    }
}
